Wet Day#

import warnings
warnings.filterwarnings("ignore")
import os
import os.path as op
import sys
import folium

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

sys.path.append("../../../../indicators_setup")
from ind_setup.plotting_int import plot_timeseries_interactive
from ind_setup.plotting import plot_bar_probs
from ind_setup.colors import get_df_col
from ind_setup.core import fontsize


sys.path.append("../../../functions")
from data_downloaders import GHCN
country = 'Palau'
vars_interest = ['PRCP']

Get Data#

update_data = False
path_data = "../../../data"
if update_data:
    df_country = GHCN.get_country_code(country)
    print(f'The GHCN code for {country} is {df_country["Code"].values[0]}')

    df_stations = GHCN.download_stations_info()
    df_country_stations = df_stations[df_stations['ID'].str.startswith(df_country.Code.values[0])]
    print(f'There are {df_country_stations.shape[0]} stations in {country}')

Using Koror Station#

if update_data:
    GHCND_dir = 'https://www.ncei.noaa.gov/data/global-historical-climatology-network-daily/access/'
    id = 'PSW00040309' # Koror Station
    dict_prcp = GHCN.extract_dict_data_var(GHCND_dir, 'PRCP', df_country_stations.loc[df_country_stations['ID'] == id])[0]
    data = dict_prcp[0]['data']#.dropna()
    data.to_pickle(op.join(path_data, 'GHCN_precipitation.pkl'))
else:
    data = pd.read_pickle(op.join(path_data, 'GHCN_precipitation.pkl'))

Analysis of wet days

dict_prcp = [{'data' : data, 'var' : 'PRCP', 'ax' : 1, 'label' : 'Precipitation'},
        ]
fig = plot_timeseries_interactive(dict_prcp, trendline=True, ylims = [None, None], figsize = (25, 12))

Wet days#

data = dict_prcp[0]['data']#.dropna()
data = data.groupby(data.index.year).filter(lambda x: len(x) >= 300).dropna()
data['wet_day'] = np.where(data['PRCP'] > 0, 1, np.where((np.isnan(data['PRCP'])==True), np.nan, 0))
ax = plot_bar_probs(x = [0, 1], y = data.groupby('wet_day').count()['PRCP'].values, labels = ['Dry Days', 'Wet Days'])
ax.set_title('Distribution of Wet Days', fontsize = fontsize)
Text(0.5, 1.0, 'Distribution of Wet Days')
../../../_images/3bb64f37e852a7f80cc339f7974e5dafa95475249aa6e920f303982ab3031e2c.png

Accumulated precipitation#

# Correct accumulated precipitation with number of observations per year to make fair comparisons and trends
datag = (data.groupby(data.index.year).sum()/ data.groupby(data.index.year).count()) * 365
datag.index = pd.to_datetime(datag.index, format = '%Y')
dict_plot = [{'data' : datag, 'var' : 'PRCP', 'ax' : 1, 'label':'Accumulated precipitation [mm]'},]
plot_timeseries_interactive(dict_plot, trendline = True, figsize = (25, 12));
ax = plot_bar_probs(x = datag.index.year, y = datag['PRCP'].values,
                    trendline = True, figsize = [15, 4])
ax.set_title('Accumulated Rainfall Over Time', fontsize = fontsize)
Text(0.5, 1.0, 'Accumulated Rainfall Over Time')
../../../_images/4fd945fe5a76427a78731edfd2f00a59841bc45465290606722a0297ace9e580.png

Number of days over and above threshold#

threshold = 1 #np.percentile(data['PRCP'].dropna(), 90)
data['wet_day_t'] = np.where(data['PRCP'] > threshold, 1, np.where((np.isnan(data['PRCP'])==True), np.nan, 0))
data_th = data.groupby([data.index.year, data.wet_day_t]).count()['PRCP']
data_th = data_th/data.groupby(data.index.year).count()['PRCP'] * 365
fig, ax = plt.subplots(figsize = [15, 5])
data_th.unstack().plot(kind = 'bar', stacked = True, ax = ax, color = get_df_col()[:2], edgecolor = 'white', alpha = .5)
ax.set_ylabel('Number of days', fontsize = fontsize)
Text(0, 0.5, 'Number of days')
../../../_images/13c511d0d27f7975f7f39e5aa6bde9c35c504eb4b28db586a76ff487a31e41f9.png
#Wet days
data2 = data.loc[data['wet_day_t'] == 1]
data2 = data2.groupby(data2.index.year).count()
plot_bar_probs(x = data2.index, y = data2.PRCP.values, trendline = True,
               y_label = 'Number of wet days', figsize = [15, 4])
<Axes: ylabel='Number of wet days'>
../../../_images/a94210698a5a722ebdeeb4598e3935249fec3ae8ba0747d14281c050dafedecd.png
#Dry days
data2 = data.loc[data['wet_day_t'] == 0]
data2 = data2.groupby(data2.index.year).count()
plot_bar_probs(x = data2.index, y = data2.PRCP.values, trendline = True,
               y_label = 'Number of dry days', figsize = [15, 4])
<Axes: ylabel='Number of dry days'>
../../../_images/9f7c599ca693831085b45665c6555e13fb24d58ec10878d2d0d47115b09494f3.png

Days over threshold#

prcentile = 95
threshold = np.round(np.percentile(data['PRCP'].dropna(), prcentile), 2)
print(f'Threshold of {threshold}mm')
data['wet_day_t'] = np.where(data['PRCP'] > threshold, 1, np.where((np.isnan(data['PRCP'])==True), np.nan, 0))
Threshold of 45.7mm
data_2 = data.loc[data['wet_day_t'] == 1][['PRCP']]
data_over_th = data_2.groupby(data_2.index.year).count()
data_over_th.index = pd.to_datetime(data_over_th.index, format = '%Y')
data_over_th['PRCP_below'] = 365 - data_over_th['PRCP'].values
dict_plot = [{'data' : data_over_th, 'var' : 'PRCP', 'ax' : 1, 'label':f'Number of days over threshold: {threshold}mm'},]
plot_bar_probs(x = data_over_th.index.year, y = data_over_th['PRCP'].values, trendline = True,
               figsize = (15, 5), y_label = f'Number of days over {prcentile} percentile')
<Axes: ylabel='Number of days over 95 percentile'>
../../../_images/4ee4008b42e56d0aa528486fc1292a69b25e9b8ca551a7f56922acc2cec59349.png
plot_bar_probs(x = data_over_th.index.year, y = data_over_th['PRCP_below'].values, trendline = True,
               figsize = (15, 5), y_label = f'Number of days below {prcentile} percentile')
<Axes: ylabel='Number of days below 95 percentile'>
../../../_images/2ecbc9fd4bdc126e9ce854329510e71ab2b5d6be6fefc943e26806d33f9453ff.png
plot_timeseries_interactive(dict_plot, trendline = True, figsize = (25, 12));
dict_plot = [{'data' : data_over_th, 'var' : 'PRCP_below', 'ax' : 1, 'label':f'Number of days below threshold: {threshold}mm'}]
plot_timeseries_interactive(dict_plot, trendline = True, figsize = (25, 12));